"""保存识别结果"""
# 1004：四位数字英文混合
import os
import logging
import requests
from scrapy.utils.project import get_project_settings
from zc_core.plugins.verify_code import VerifyCode
from zc_core.util.common import random_code

logger = logging.getLogger('captcha')


def verify_code(key):
    settings = get_project_settings()
    base_path = os.path.join(settings.get('OUTPUT_ROOT'), 'verify_code\\')
    if not os.path.exists(base_path):
        os.makedirs(base_path)

    file = os.path.join(base_path, '%s.png' % key)

    r = requests.get(
        'http://210.76.73.185/rucaptcha/?format=html',
        headers={
            'Referer': 'http://210.76.73.185/more_notices.html?_rucaptcha={}'.format(key),
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
            'Cookie': '_gdddxt_session=26ba894749c92eba143e629b91969999'
        }
    )
    session_id = r.cookies.get('_gdddxt_session', '')

    img = r.content
    with open(file, 'wb') as f:
        f.write(img)

    code = VerifyCode().verify(file, code_type='1005')
    if code:
        new_file = os.path.join(base_path, '%s_%s.png' % (key, code))
        os.rename(file, new_file)
        logger.info('key={}, code={}, session_id={}'.format(key, code, session_id))
        return code.lower(), session_id

    return None, None

if __name__ == '__main__':
    key = random_code().lower()
    code, session_id = verify_code(key)
    print('key={}'.format(key))
    print('code={}'.format(code))
    print('session_id={}'.format(session_id))
